package com.topscore.uke.ui.activities;

import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.topscore.uke.R;
import com.topscore.uke.entities.TeamPerformanceListEntity;
import com.topscore.uke.mvp.contractors.GetTeamPerformanceRankContractor;
import com.topscore.uke.mvp.contractors.TeamPerformanceRankContractor;
import com.topscore.uke.mvp.presenters.GetTeamPerformanceRankPresenter;
import com.topscore.uke.mvp.presenters.TeamPerformanceRankPresenter;
import com.topscore.uke.ui.ToolBarCompatActivity;
import com.topscore.uke.ui.dialog.MonthSelector;
import com.topscore.uke.utils.SnackBarUtil;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.ComboLineColumnChartData;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.view.ComboLineColumnChartView;

public class TeamPerformanceActivity extends ToolBarCompatActivity implements
        View.OnClickListener,
        MonthSelector.OnMonthSelectedListener, GetTeamPerformanceRankContractor.View {

    @Bind(R.id.year)
    TextView yearTv;
    @Bind(R.id.combo_line_column_chart_view)
    ComboLineColumnChartView comboLineColumnChartView;
    @Bind(R.id.toolbar_layout)
    CollapsingToolbarLayout toolbarLayout;
    @Bind(R.id.app_bar)
    AppBarLayout appBar;
    @Bind(R.id.order_ranking)
    LinearLayout orderRanking;
    @Bind(R.id.order_turnover)
    LinearLayout orderTurnover;
    @Bind(R.id.order_volume)
    LinearLayout orderVolume;
    @Bind(R.id.list_recycler)
    RecyclerView listRecycler;
    @Bind(R.id.total_amount)
    TextView totalAmountTv;
    @Bind(R.id.total_count)
    TextView totalCountTv;
    @Bind(R.id.date_select)
    TextView dateSelect;
    @Bind(R.id.date_select_layout)
    RelativeLayout dateSelectLayout;

    private ComboLineColumnChartData mChartData;

    private ListAdapter mListAdapter;

    private View mEmptyView;

    private MonthSelector mMonthSelector;

    private GetTeamPerformanceRankPresenter mPerformanceRankPresenter;

    //    private GetTeamPerformanceContractor.Presenter mGetPerformancePresenter;
//    private TeamPerformanceRankContractor.Presenter mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_team_performance);
        ButterKnife.bind(this);
        mPerformanceRankPresenter = new GetTeamPerformanceRankPresenter(this);
//        mPresenter = new TeamPerformanceRankPresenter(this);
//        mGetPerformancePresenter = new GetTeamPerformancePresenter(this);
        initViews();
    }

    private void initViews() {
        setCentralTitle("团队业绩");
        listRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        listRecycler.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mListAdapter = new ListAdapter();
        listRecycler.setAdapter(mListAdapter);
        dateSelectLayout.setOnClickListener(this);
        yearTv.setText(mPerformanceRankPresenter.getCurrentYear());
        initData();
    }

    private void initData() {
        mPerformanceRankPresenter.getPerformanceRank();
//        mPresenter.getData();
//        mGetPerformancePresenter.getPerformanceInYear("2017","m1003");
//        mChartData = new ComboLineColumnChartData();
//        AssetManager assetManager = getApplication().getAssets();
//        Axis axisX;
//        List<AxisValue> axisValues;
//        List<Column> columnList;
//        List<Line> lines;
//        try {
//            InputStream inputStream = assetManager.open("performance.json");
//            byte[] buffer = new byte[inputStream.available()];
//            inputStream.read(buffer);
//            String json = new String(buffer, "utf-8");
//            inputStream.close();
//            PerformanceData data = new Gson().fromJson(json, PerformanceData.class);
//            axisValues = new ArrayList<>();
//            lines = new ArrayList<>();
//            List<PointValue> points = new ArrayList<>();
//            for (int i = 0; i < data.getSaleCounts().size(); i++) {
//                axisValues.add(new AxisValue(i).setLabel(data.getSaleCounts().get(i).getX()));
//                PointValue point = new PointValue(i, data.getSaleCounts().get(i).getY());
//                points.add(point);
//            }
//            axisX = new Axis(axisValues);
//            Line line = new Line(points);
//            line.setColor(Color.parseColor("#f8b551"));
//            line.setHasLines(true);
//            line.setHasPoints(true);
//            line.setCubic(false);
////        line.setPointColor(Color.WHITE);
//            line.setStrokeWidth(1);
//            line.setShape(ValueShape.CIRCLE);
//            line.setPointRadius(3);
//            lines.add(line);
//            mChartData.setLineChartData(new LineChartData(lines));
//
//
//            columnList = new ArrayList<>();
//            for (int i = 0; i < data.getSaleMoneys().size(); i++) {
//                List<SubcolumnValue> columnValueList = new ArrayList<>();
//                SubcolumnValue value = new SubcolumnValue(data.getSaleMoneys().get(i).getY(), getResources().getColor(R.color.colorPrimary));
//                columnValueList.add(value);
//                columnList.add(new Column(columnValueList));
//            }
//            ColumnChartData columnChartData = new ColumnChartData(columnList);
//            mChartData.setColumnChartData(columnChartData);
//            mChartData.setAxisXBottom(axisX);
//            comboLineColumnChartView.setComboLineColumnChartData(mChartData);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

//        initListData();
//        Axis axisX = new Axis();
//        mChartData.setAxisXBottom(axisX);
//        mChartData.setLineChartData(generateLineData());
//        mChartData.setColumnChartData(generateColumnData());
//        comboLineColumnChartView.setComboLineColumnChartData(mChartData);
    }

    private ColumnChartData generateColumnData() {
        List<Column> columnList = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            List<SubcolumnValue> valueList;
            valueList = new ArrayList<>();
            valueList.add(new SubcolumnValue((float) Math.random() * 50 + 5, getResources().getColor(R.color.colorPrimary)));
            columnList.add(new Column(valueList));
        }
        ColumnChartData data = new ColumnChartData(columnList);
        return data;
    }

    private LineChartData generateLineData() {
        List<Line> lines = new ArrayList<>();
        List<PointValue> pointValueList = new ArrayList<>();
        List<AxisValue> axisValues = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            PointValue pointValue = new PointValue(i, (float) Math.random() * 50 + 5);
            AxisValue axisValue = new AxisValue(i).setLabel(i + "月份");
            axisValues.add(axisValue);
            pointValueList.add(pointValue);
        }
        Line line = new Line(pointValueList);
        line.setColor(Color.parseColor("#f8b551"));
        line.setHasLines(true);
        line.setHasPoints(true);
        line.setCubic(false);
//        line.setPointColor(Color.WHITE);
        line.setStrokeWidth(1);
        line.setShape(ValueShape.CIRCLE);
        line.setPointRadius(3);
        lines.add(line);
        LineChartData data = new LineChartData(lines);
        mChartData.setAxisXBottom(new Axis(axisValues));
        return data;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.date_select_layout:
                if (mMonthSelector == null) {
                    mMonthSelector = new MonthSelector(mContext, this);
                }
                mMonthSelector.show();
                break;
        }
    }

    @Override
    public void onSelectYear(String year) {
        yearTv.setText(year);
        dateSelect.setText("全年");
        mPerformanceRankPresenter.getPerformanceRank(year);
//        mPresenter.getPerformanceByYear(year);
    }

    @Override
    public void onSelectMonth(String year, String month) {
        yearTv.setText(year + "-" + month);
        dateSelect.setText("月份");
        mPerformanceRankPresenter.getPerformanceRank(year, month);
//        mPresenter.getPerformanceByMonth(month);
    }

    @Override
    public void onSelectCurrentYear() {
        yearTv.setText(new SimpleDateFormat("YYYY").format(new Date()));
        dateSelect.setText("本年");
        mPerformanceRankPresenter.getPerformanceRank(mPerformanceRankPresenter.getCurrentYear());
//        mPresenter.getPerformanceByYear();
    }

    @Override
    public void onSelectCurrentMonth() {
        yearTv.setText(new SimpleDateFormat("YYYY-MM").format(new Date()));
        dateSelect.setText("本月");
        mPerformanceRankPresenter.getPerformanceRank(mPerformanceRankPresenter.getCurrentYear(), mPerformanceRankPresenter.getCurrentMonth());
//        mPresenter.getPerformanceByMonth();
    }

    @Override
    public BaseQuickAdapter getRankAdapter() {
        return mListAdapter;
    }

    @Override
    public ComboLineColumnChartView getLineColumnChartView() {
        return comboLineColumnChartView;
    }

    @Override
    public void onGetPerformanceChartDataSuccess(ComboLineColumnChartData lineColumnChartData) {
        comboLineColumnChartView.setComboLineColumnChartData(lineColumnChartData);
    }

    @Override
    public TextView getTotalAmountTv() {
        return totalAmountTv;
    }

    @Override
    public TextView getTotalSalesCountTv() {
        return totalCountTv;
    }

    @Override
    public void onLoading(String loadingMessage) {
        showLoadingDialog(loadingMessage);
    }

    @Override
    public void onLoadFinished() {
        dismissLoadingDialog();
    }

    @Override
    public void onFail(int code, String errorMessage) {
        Toast.makeText(mContext, errorMessage, Toast.LENGTH_SHORT).show();
    }
//
//    @Override
//    public void onGetPerformanceSuccess(PerformanceData performanceData) {
//
//    }
//
//    @Override
//    public void onGetPerformanceCharDataSuccess(ComboLineColumnChartData chartData) {
//        mChartData = chartData;
//        comboLineColumnChartView.setComboLineColumnChartData(mChartData);
//    }

    private class ListAdapter extends BaseQuickAdapter<TeamPerformanceListEntity, BaseViewHolder> {
        public ListAdapter() {
            super(R.layout.team_performance_item_layout, new ArrayList<>());
            mEmptyView = getLayoutInflater().inflate(R.layout.rank_empty_view, (ViewGroup) listRecycler.getParent(), false);
            setEmptyView(mEmptyView);
        }

        @Override
        protected void convert(BaseViewHolder holder, TeamPerformanceListEntity item) {
//            ImageLoader.getInstance().displayImage(item.getUserPhoto(), (ImageView) holder.getView(R.id.avatar_iv));
            holder.setText(R.id.name_tv, item.getShareUserName())
                    .setText(R.id.turnover_tv, new DecimalFormat("0.00").format(item.getSalesAmount()))
                    .setText(R.id.volume_tv, String.valueOf(item.getSalesCount()));
        }
    }
}
